package com.aceleeyy.sevenstar.controller;

import com.aceleeyy.sevenstar.config.ErrorMessage;
import com.aceleeyy.sevenstar.config.SevenStarCommonInfo;
import com.aceleeyy.sevenstar.dao.BookListMapper;
import com.aceleeyy.sevenstar.dao.MagazineMapper;
import com.aceleeyy.sevenstar.dao.MagazinePicturesMapper;
import com.aceleeyy.sevenstar.model.*;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 书架管理
 *
 * @auther: Ace Lee
 * @date: 2019/10/26 10:43
 */
@Api(value = "书架管理", description = "书架管理")
@Slf4j
@RestController
@RequestMapping("booklists")
public class BookListController extends BaseController {

    @Autowired
    private BookListMapper bookListMapper;
    @Autowired
    private MagazineMapper magazineMapper;
    @Autowired
    private MagazinePicturesMapper magazinePicturesMapper;

    /**
     * 我的书架
     *      openid: 用户微信标识
     *
     * @param request
     * @param openid
     * @return
     */
    @ApiOperation(value = "我的书架")
    @GetMapping("/{openid}")
    public Result get(HttpServletRequest request, @PathVariable String openid) {
        Result result;
        log.info("我的书架请求参数：{}", openid);
        if (StringUtils.isEmpty(openid)) {
            return Result.error(ErrorMessage.E_001.getErrDesc());
        }

        try {
            UserInfo userInfo = getUserByOpenid(openid);
            if (null==userInfo){
                return Result.error(ErrorMessage.E_004.getErrDesc());
            }
            List<Magazine> list = magazineMapper.selectByUserId(userInfo.getId());
            if (!CollectionUtils.isEmpty(list)){
                log.info("我的书架结果：{}", list.size());
                list.forEach(magazine -> {
                    List<MagazinePictures> pictures = magazinePicturesMapper.selectByMagazineId(magazine.getId());
                    magazine.setPictures(pictures);
                });
            }
            result = new Result<>(list);
        } catch (Exception e) {
            log.error("我的书架异常：{}", Throwables.getStackTraceAsString(e));
            result = Result.error(ErrorMessage.E_999.getErrDesc());
        }
        return result;
    }

    /**
     * 加入书架
     *      openid: 用户微信标识
     *      magazineid: 杂志id
     *
     * @param request
     * @param params
     * @return
     */
    @ApiOperation(value = "加入书架")
    @PostMapping("")
    public Result post(HttpServletRequest request, @RequestBody Map<String,Object> params) {
        Result result;
        log.info("加入书架请求参数：{}", params);
        if (null == params || null == params.get("openid") || null == params.get("magazineid")) {
            return Result.error(ErrorMessage.E_001.getErrDesc());
        }

        try {
            String openid = (String) params.get("openid");
            Integer magazineid = (Integer) params.get("magazineid");
            UserInfo userInfo = getUserByOpenid(openid);
            if (null==userInfo){
                return Result.error(ErrorMessage.E_004.getErrDesc());
            }
            //加入书架
            BookList record = new BookList();
            record.setUserId(userInfo.getId());
            record.setMagazineId(magazineid);
            //如果以前加入过的，更新状态为有效，没有则新增
            BookList exist = bookListMapper.selectByUserIdAndMagazineId(record);
            if (null==exist){
                record.setMagazinePage(0);
                record.setCreatedTime(new Date());
                record.setIsValid(SevenStarCommonInfo.BOOLEAN_YES);
                int add = bookListMapper.insertSelective(record);
                log.info("加入书架不存在结果：{}", add);
            }else {
                record = new BookList();
                record.setId(exist.getId());
                record.setIsValid(SevenStarCommonInfo.BOOLEAN_YES);
                record.setUpdatedTime(new Date());
                int upd = bookListMapper.updateByPrimaryKeySelective(record);
                log.info("加入书架存在结果：{}", upd);
            }

            //更新杂志是否在书架
            Magazine magazine = new Magazine();
            magazine.setId(magazineid);
            magazine.setIsInBooklist(SevenStarCommonInfo.BOOLEAN_YES);
            magazine.setUpdatedTime(new Date());
            int update = magazineMapper.updateByPrimaryKeySelective(magazine);
            log.info("加入书架更新杂志是否在书架结果：{}", update);

            result = new Result<>(update);
        } catch (Exception e) {
            log.error("加入书架异常：{}", Throwables.getStackTraceAsString(e));
            result = Result.error(ErrorMessage.E_999.getErrDesc());
        }
        return result;
    }

    /**
     * 移除书架
     *      openid: 用户微信标识
     *      magazineid: 杂志id
     *
     * @param request
     * @param params
     * @return
     */
    @ApiOperation(value = "移除书架")
    @DeleteMapping("")
    public Result delete(HttpServletRequest request, @RequestBody Map<String,Object> params) {
        Result result;
        log.info("移除书架请求参数：{}", params);
        if (null == params || null == params.get("openid") || null == params.get("magazineid")) {
            return Result.error(ErrorMessage.E_001.getErrDesc());
        }

        try {
            Integer magazineid = (Integer) params.get("magazineid");
            String openid = (String) params.get("openid");
            UserInfo userInfo = getUserByOpenid(openid);
            if (null==userInfo){
                return Result.error(ErrorMessage.E_004.getErrDesc());
            }
            BookList record = new BookList();
            record.setMagazineId(magazineid);
            record.setUserId(userInfo.getId());
            BookList exist = bookListMapper.selectByUserIdAndMagazineId(record);
            if (null!=exist){
                record = new BookList();
                record.setId(exist.getId());
                record.setIsValid(SevenStarCommonInfo.BOOLEAN_NO);
                record.setUpdatedTime(new Date());
                int upd = bookListMapper.updateByPrimaryKeySelective(record);
                log.info("移除书架结果：{}", upd);
            }

            //更新杂志是否在书架
            Magazine magazine = new Magazine();
            magazine.setId(magazineid);
            magazine.setIsInBooklist(SevenStarCommonInfo.BOOLEAN_NO);
            magazine.setUpdatedTime(new Date());
            int update = magazineMapper.updateByPrimaryKeySelective(magazine);
            log.info("移除书架更新杂志是否在书架结果：{}", update);
            result = new Result<>(update);
        } catch (Exception e) {
            log.error("移除书架异常：{}", Throwables.getStackTraceAsString(e));
            result = Result.error(ErrorMessage.E_999.getErrDesc());
        }
        return result;
    }

    /**
     * 我最近的阅读
     *      openid: 用户微信标识
     *
     * @param request
     * @param openid
     * @return
     */
    @ApiOperation(value = "我最近的阅读")
    @GetMapping("/read/{openid}")
    public Result getRead(HttpServletRequest request, @PathVariable String openid) {
        Result result;
        log.info("我最近的阅读请求参数：{}", openid);
        if (StringUtils.isEmpty(openid)) {
            return Result.error(ErrorMessage.E_001.getErrDesc());
        }

        try {
            List<Magazine> resList = Lists.newArrayList();
            UserInfo userInfo = getUserByOpenid(openid);
            if (null==userInfo){
                return Result.error(ErrorMessage.E_004.getErrDesc());
            }
            List<BookList> list = bookListMapper.selectMyReads(userInfo.getId());
            if (!CollectionUtils.isEmpty(list)){
                for (BookList bookList : list) {
                    Magazine magazine = magazineMapper.selectByPrimaryKey(bookList.getMagazineId());
                    if (null!=magazine){
                        magazine.setMagazinePage(bookList.getMagazinePage());
                        resList.add(magazine);
                    }
                }
            }

            if (!CollectionUtils.isEmpty(resList)){
                log.info("我最近的阅读结果：{}", resList.size());
                resList.forEach(magazine -> {
                    if (null!=magazine){
                        List<MagazinePictures> pictures = magazinePicturesMapper.selectByMagazineId(magazine.getId());
                        magazine.setPictures(pictures);
                    }
                });
            }

            result = new Result<>(resList);
        } catch (Exception e) {
            log.error("我最近的阅读异常：{}", Throwables.getStackTraceAsString(e));
            result = Result.error(ErrorMessage.E_999.getErrDesc());
        }
        return result;
    }

    /**
     * 加入阅读
     *      openid: 用户微信标识
     *      magazineid: 杂志id
     *      magazinepage: 杂志页数
     *
     * @param request
     * @param params
     * @return
     */
    @ApiOperation(value = "加入阅读")
    @PostMapping("/read")
    public Result read(HttpServletRequest request, @RequestBody Map<String,Object> params) {
        Result result;
        int read = 0;
        log.info("加入阅读请求参数：{}", params);
        if (null == params || null == params.get("openid") || null == params.get("magazineid")) {
            return Result.error(ErrorMessage.E_001.getErrDesc());
        }

        try {
            Date now = new Date();
            String openid = (String) params.get("openid");
            Integer magazineid = (Integer) params.get("magazineid");
            Integer magazinepage = (Integer)params.get("magazinepage");
            UserInfo userInfo = getUserByOpenid(openid);
            if (null==userInfo){
                return Result.error(ErrorMessage.E_004.getErrDesc());
            }
            //加入书架
            BookList record = new BookList();
            record.setUserId(userInfo.getId());
            record.setMagazineId(magazineid);
            BookList exist = bookListMapper.selectByUserIdAndMagazineId(record);
            if (null==exist){
                record.setMagazinePage(0);
                record.setCreatedTime(now);
                record.setUpdatedTime(now);
                record.setIsValid(SevenStarCommonInfo.BOOLEAN_NO);
                read = bookListMapper.insertSelective(record);
                log.info("加入阅读不存在结果：{}", read);
            }else {
                record = new BookList();
                record.setId(exist.getId());
                record.setMagazinePage(magazinepage);
                record.setUpdatedTime(now);
                read = bookListMapper.updateByPrimaryKeySelective(record);
                log.info("加入阅读存在结果：{}", read);
            }

            result = new Result<>(read);
        } catch (Exception e) {
            log.error("加入阅读异常：{}", Throwables.getStackTraceAsString(e));
            result = Result.error(ErrorMessage.E_999.getErrDesc());
        }
        return result;
    }


    /**
     * 清除最近阅读
     *      openid: 用户微信标识
     *
     * @param request
     * @param openid
     * @return
     */
    @ApiOperation(value = "清除最近阅读")
    @DeleteMapping("/read/{openid}")
    public Result deleteRead(HttpServletRequest request, @PathVariable String openid) {
        Result result;
        log.info("清除最近阅读请求参数：{}", openid);
        if (StringUtils.isEmpty(openid)) {
            return Result.error(ErrorMessage.E_001.getErrDesc());
        }

        try {
            UserInfo userInfo = getUserByOpenid(openid);
            if (null == userInfo) {
                return Result.error(ErrorMessage.E_004.getErrDesc());
            }

            int update = bookListMapper.deleteMyReads(userInfo.getId());
            log.info("清除最近阅读结果：{}", update);
            result = new Result<>(update);
        } catch (Exception e) {
            log.error("清除最近阅读异常：{}", Throwables.getStackTraceAsString(e));
            result = Result.error(ErrorMessage.E_999.getErrDesc());
        }
        return result;
    }

}
